<?php

namespace app\common\controller;

use Mrgoon\AliSms\AliSms;
use think\Controller;
use think\Db;
use think\Env;

/**
 * 前台控制器基类
 */
class ExpertSms extends Controller
{
    /**
     * 发送专家短信
     */
    public function sendExpertSms($project, $expert)
    {
        $config = [
            'access_key' => Env::get('sms.access_key'),
            'access_secret' => Env::get('sms.access_secret'),
            'sign_name' => Env::get('sms.sign_name'),
        ];

        foreach ($expert as $k => $v) {
            $expert_id = $v['expert_id']; //专家id
            $project_id =  $v['project_id']; //项目id
            $expertInfo = Db::name('expert')->where('id', $expert_id)->find();
            $send_data = ['name' => $expertInfo['name'], 'company' => $project['agent'], 'project' => $project['name'], 'time1' => date('Y-m-d H:i', $project['review_time'])];
            $lastRecord = Db::name('projectexpert')->where(['expert_id' => $expert_id, 'project_id' => $project_id])->order('createtime', 'desc')->find();
            if (!empty($expertInfo)) {
                $aliSms = new AliSms();
                $response = $aliSms->sendSms($expertInfo['contact_tel'], Env::get('sms.tempplate_code'), $send_data, $config);

                $send_params = [
                    'send_params_phone' => $expertInfo['contact_tel'],
                    'send_params_name' => $expertInfo['name'],
                    'send_params_project' => $project['name'],
                    'send_params_company' => $project['agent'],
                    'send_params_time1' => $project['review_time']
                ];
                if (isset($response->Code) && $response->Code != 'OK' && $response->Message != 'OK') {
                    $send_other_params = ['send_result' => json_encode($response), 'send_time' => time(), 'sms_status' => 3, 'send_fail_reason' => $response->Message];
                    $mergedArray = array_merge($send_params, $send_other_params);
                    Db::name('projectexpert')->where('id', $lastRecord['id'])->update($mergedArray);
                } else {
                    $send_other_params = ['send_result' => json_encode($response), 'send_time' => time(), 'sms_status' => 2];
                    $mergedArray = array_merge($send_params, $send_other_params);
                    Db::name('projectexpert')->where('id', $lastRecord['id'])->update($mergedArray);
                }
            } else {
                //专家不存在
                Db::name('projectexpert')->where('id', $lastRecord['id'])->update(['send_params' => json_encode($send_data), 'sms_status' => 3, 'send_fail_reason' => '专家不存在']);
            }
        }
    }
}
